import {Component, OnInit} from '@angular/core';
import {UserService} from '../../user/service/user.service';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {Blog} from '../model/blog';
import {Message} from 'primeng/components/common/api';


@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
  blog: Blog = null;
  canVote: boolean;
  msgs: Message[] = [];
  count: number;

  constructor(public http: HttpClient, public router: Router,
              public route: ActivatedRoute, public userService: UserService) {
  }

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      if (params['id']) {
        this.http.get('/blog?id=' + params['id']).subscribe((result: any) => {
          if (result.error) {
            this.router.navigateByUrl('/');
          } else {
            this.blog = result['data'];
          }
        });
      } else {
        this.router.navigateByUrl('/');
      }
    });
  }


  deleteBlogById(id) {
    this.http.delete('/blog?id=' + id).subscribe(result => {
      if (result['error']) {
        this.msgs = [];
        this.msgs.push({severity: 'error', summary: '登录过期了,请重新登录!', detail: result['error']});
        this.userService.currentUser = null;
        this.router.navigateByUrl('/user/login');
      } else {
        this.router.navigateByUrl('/');
      }

    });
  }

  addVote(blogId) {

  }

  deleteVote(blogId) {

  }

  addComment(blogId, content: string) {
    if (content == '') {
      this.msgs = [];
      this.msgs.push({severity: 'error', summary: '评论不能为空'});
      return;
    }
    this.http.post('/comment', null, {
      params: {blogId: blogId, content: content}
    }).subscribe(result => {
      if (result['error'] == '未登录') {
        this.userService.currentUser=null;
        this.router.navigateByUrl('/user/login');
      } else {
        this.blog = result['data'];
      }
    });

  }

  deleteComment(blogId, commentId) {
    this.http.delete('/comment', {
      params: {
        blogId: blogId, commentId: commentId
      }
    }).subscribe(result => {
      if (result['error'] == '未登录') {
        this.userService.currentUser=null;
        this.router.navigateByUrl('/user/login');
      }
      if (result['error'] == '') {
        this.blog = result['data'];
        this.msgs = [];
        this.msgs.push({severity: 'error', summary: '删除评论成功'});
      }
    });
  }

  showMessage() {
    console.log('in showMessage()');
    this.msgs = [];
    this.msgs.push({severity: 'error', summary: '登录失败,用户名或者密码不对!', detail: 'test     test'});
  }


}
